package HTTP

import (
	//"fmt"

	"SQL/myDB"
	"database/sql"
	"errors"
	"logs"
	"net/http"
)

func setData(w http.ResponseWriter, req *http.Request) {
	printRequestInfo(req)
	w.Header().Set("Content-Type", "text/html;charset=utf-8")
	w.Write([]byte(`
<!DOCTYPE html>
<html>
<head>
<title>设置数据成功</title>
</head>
<body>
	`))
	defer w.Write([]byte(`
<body>
</html>
	`))

	err := req.ParseForm()
	if err != nil {
		logs.Print("setData error:", err.Error())
		w.Write([]byte(err.Error()))
		return
	}

	page := req.FormValue("page")
	err = resetDB(page)
	if err != nil {
		logs.Print("setData error:", err.Error())
		w.Write([]byte(err.Error()))
		return
	}

	w.Write([]byte(`
	<script>window.location.href="/dbPage"</script> 
	<a href=/dbPage>若没有跳转请点这里</a>
	`))
}

func resetDB(page string) error {

	db, err := myDB.GetDB()
	if err != nil {
		return err
	}
	switch page {
	case "resetDB":
		err = createTables(db)
	case "copyDB":
		err = copyDB(db)
	default:
		err = errors.New("page not exists")
	}
	return err
}

func createTables(db *sql.DB) error {
	Sql := []string{

		`--1.objects(id int64 pk,nickname string,iconURL string,isUser bool,custom jsonb)

create table if not exists objects (
	id serial8 primary key,
	nickname varchar(200) not null,			--nickname修改为not null
	iconURL varchar(500),						--若为空服务端赋值为icon
	isUser bool not null,
	custom jsonb
);
--例子：
`, `select setval('objects_id_seq',10000);--设置起始值
`, `insert into objects(nickname,iconURL,isUser,custom) values('用户1','icon1',true,'{"sex":"female","age":18,"同学":"[10003,10002]"}'::json);
`, `insert into objects(nickname,iconURL,isUser,custom) values('测试用户2','icon2',true,'{"sex":"male","age":19,"崇拜的人":"[10004]","同学":"[10003,10001]"}'::json);
`, `insert into objects(nickname,iconURL,isUser,custom) values('TestUser3','icon3',true,'{"sex":"female","age":20,"男朋友":"[10004]","同学":"[10001,10002]"}'::json);
`, `insert into objects(nickname,iconURL,isUser,custom) values('User4','icon4',true,'{"sex":"male","age":22,"女朋友":"[10003]"}'::json);
`, `insert into objects(nickname,iconURL,isUser,custom) values('嵌入式讨论群5','icon5',false,'{"地址":"广州"}'::json);
`, `insert into objects(nickname,iconURL,isUser,custom) values('吹水群6','icon6',false,'{"地址":"佛山","群组类型":"闲聊"}'::json);
`,

		`--2.users(id int64 fk pk,account string unique,password string,isManager bool)

create table if not exists users (
	id int8 references objects(id) on delete cascade,
	account varchar(200) unique,
	password varchar(200) not null,
	isManager bool not null,
	primary key(id)
);

--例子：
`, `insert into users(id,password,isManager) values(10001,'123456',false);
`, `insert into users(id,password,isManager) values(10002,'123456',true);
`, `insert into users(id,password,isManager) values(10003,'123456',true);
`, `insert into users(id,password,isManager) values(10004,'123456',false);
`,

		`--3.groups(id int64 fk pk,createtime time)

create table if not exists groups (
	id int8 references objects(id) on delete cascade,
	createTime timestamp with time zone default now(),
	primary key(id)
);

--例子：
`, `insert into groups(id) values(10005);
`, `insert into groups(id) values(10006);
`,

		`--4.members(groupID int64 fk,userID int64 fk,pk(groupID,userID))

create table if not exists members (
	groupID int8 references objects(id) on delete cascade,
	userID int8 references objects(id) on delete cascade,
	primary key(groupID,userID)
);

--例子：
`, `insert into members(groupID,userID) values (10005,10001),(10005,10002),(10005,10004);
`, `insert into members(groupID,userID) values (10006,10001),(10006,10002),(10006,10003);
`,

		`--5.messages(id int64 pk,content string,sender int64 fk,receiver int64 fk,createTime time)

create table if not exists messages (
	id serial8 primary key,
	content varchar(2000) not null,
	sender int8 references objects(id) on delete cascade,
	receiver int8 references objects(id) on delete cascade,
	createTime timestamp with time zone default now()
);

--例子：
`, `insert into messages(content,sender,receiver) values('10001:你好 user2!我要给你发一条很长的消息，然后让你可以测试一下你的消息气泡的高度是不是有问题！',10001,10002);
`, `insert into messages(content,sender,receiver) values('10002:嘿 user1!在吗？',10002,10001);
`, `insert into messages(content,sender,receiver) values('10002:嘿 user4!呃，没事。。。',10002,10004);
`, `insert into messages(content,sender,receiver) values('10003:你好 user1! user1。。。。。。。',10003,10001);
`, `insert into messages(content,sender,receiver) values('10001:嘿 group5!我要给你发一条很长的消息，然后让你可以测试一下你的消息气泡的高度是不是有问题！正常吗？',10001,10005);
`, `insert into messages(content,sender,receiver) values('10001:嘿 group6!呃，我来测试一下你的消息气泡的高度是不是有问题！',10001,10006);
`, `insert into messages(content,sender,receiver) values('10002:嗨 group5!我要给你发一条很长很长很长的消息，然后让你可以测试一下你的消息气泡的高度是不是有问题！正常吗？要不然，我再说点啥？你再看下，现在看下正常不？？？？？？？',10002,10005);
`, `insert into messages(content,sender,receiver) values('10003:嗨 group6! 1.0版本啥时候诞生呢？',10003,10006);
`, `insert into messages(content,sender,receiver) values('10004:你好 group6!我也要给你发一条，一条很长很长的消息，然后让你可以测试一下你的消息气泡的高度是不是有问题！正常了吧？',10004,10006);
`,

		`--6.sessions(senderID int64 fk,receiverID  int64 fk,lastMsgID int64 fk,pk(senderID,receiverID))；
create table if not exists sessions (
	senderID int8 references objects(id) on delete cascade,
	receiverID int8 references objects(id) on delete cascade,
	lastMsgID int8 references messages(id) on delete cascade,
	primary key (senderID,receiverID)
);
`,
		`--7.friends(userID int64 fk,friendID int64 fk,remark string,pk(userID,friendID)) remark指备注名
create table if not exists friends (
	userID int8 references objects(id) on delete cascade,
	friendID int8 references objects(id) on delete cascade,
	remark varchar(200),
	primary key (userID,friendID)
);
`,
	}
	return execSql(Sql, db)
}
func copyDB(db *sql.DB) error {
	Sql := []string{
		`truncate objects cascade`,
		`select setval('objects_id_seq',1000000);--设置起始值`,
		"copy objects(id,nickname,icon,isUser,custom) from '/home/ubuntu/objects.txt'",
		"copy groups(id) from '/home/ubuntu/groups.txt'",
		"copy users(id,password,isManager) from '/home/ubuntu/users.txt'",
	}
	return execSql(Sql, db)
}

func execSql(Sql []string, db *sql.DB) error {
	for _, val := range Sql {
		_, err := db.Exec(val)
		if err != nil {
			return err
		}
	}
	return nil
}
